import { find, Node } from "cc";

export class guideUtil {

    static findNodes(locator: string): Node[] {
        //使用正则表达示分隔名字
        let names = locator.split(/[//,>]/g);
        let index = 0;
        let segments = names.map(name => {
            let symbol = locator[index - 1] || '>';
            index += name.length + 1;
            return { symbol: symbol, name: name.trim() };
        });
        return this.locateNode(segments);
    }

    private static locateNode(segments: any[]): Node[] {
        let nodes = [];
        //从Canvas查找，可配置
        let root = find('Canvas');
        let searchNodes: Node[] = [root];
        for (let i = 0; i < segments.length; i++) {
            let item = segments[i];
            let isMulti = item.name[0] == '*';
            let name = item.name.replace("*", "");

            let tempNode: Node[] = [];
            searchNodes.forEach(searchNode => {
                //判断是否查找多节点
                if (isMulti) {
                    if (item.symbol == "/") {
                        searchNode.children.forEach(child => {
                            if (child.name == name && tempNode.indexOf(child) < 0) {
                                tempNode.push(child);
                            }
                        })
                    } else {
                        console.error("多节点查找只支持绝对路径");
                    }
                } else {
                    var node;
                    switch (item.symbol) {
                        //绝对路径查找
                        case '/':
                            node = searchNode.getChildByName(name);
                            break;
                        //模糊搜索
                        case '>':
                            node = this.seekNodeByName(searchNode, name);
                            break;
                        default:
                            console.error(`未注册的解析类型:${item.symbol}`);
                            break;
                    }
                    if (node && tempNode.indexOf(node) < 0)
                        tempNode.push(node);
                }
            });

            if (i == segments.length - 1) {
                nodes = tempNode;
            } else {
                searchNodes = tempNode;
            }
        }
        return nodes;
    }

    //通过节点名搜索节点对象
    private static seekNodeByName(root: Node, name: string) {
        if (!root)
            return null;

        if (root.name == name)
            return root;

        let length = root.children.length;
        for (let i = 0; i < length; i++) {
            let child = root.children[i];
            let res = this.seekNodeByName(child, name);
            if (res != null)
                return res;
        }
        return null;
    }
}


